package dobest.ray.com.jiongjiong;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.toolbox.ImageLoader;
import com.danikula.videocache.HttpProxyCacheServer;
import com.dobest.ray.corelibs.Configuration;
import com.dobest.ray.corelibs.cache.BitmapLruCache;
import com.dobest.ray.corelibs.cache.DataCache;
import com.dobest.ray.corelibs.http.RequestManager;
import com.dobest.ray.corelibs.utils.ToastMgr;
import com.facebook.drawee.backends.pipeline.Fresco;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import dobest.ray.com.jiongjiong.activity.wanttoknow.consult.ImagePagerActivity;
import dobest.ray.com.jiongjiong.constants.Paths;
import dobest.ray.com.jiongjiong.utils.ACacheHelper;
import io.rong.imkit.RongContext;
import io.rong.imkit.RongIM;
import io.rong.imkit.widget.provider.CameraInputProvider;
import io.rong.imkit.widget.provider.ImageInputProvider;
import io.rong.imkit.widget.provider.InputProvider;
import io.rong.imkit.widget.provider.VoIPInputProvider;
import io.rong.imlib.ipc.RongExceptionHandler;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.UserInfo;
import io.rong.message.ImageMessage;

/**
 * Created by Ray on 2016/2/20.
 */
public class App extends Application {

    static App instance;


    public final boolean isDebug = false;// 是否为调试模式
    public ImageLoader mImageLoader;
    public DataCache dataCache;
    public DataCache userCache;

    public String[] floorNos;
    public String authKey = "";

    public String[] getFloorNos() {
        return floorNos;
    }

    public void setFloorNos(String[] floorNos) {
        this.floorNos = floorNos;
    }

    private final int RATE = 8; // 默认分配最大空间的几分之一

    public String uid = "158";


    /**
     * 测试模式
     */
    public static boolean debug = true;

    private String city;

    /**
     * 是否打开水印
     */
    private boolean isOpenWaterMark = true;

    public boolean getIsOpenWaterMark() {
        return isOpenWaterMark;
    }

    public App() {
        instance = this;
    }

    public static synchronized App getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        init();
    }

    private void init() {
        Configuration.setShowNetworkJson(true);
        Configuration.setShowNetworkParams(true);
        RequestManager.init(this, Paths.HttpCache);
        // 确定在LruCache中，分配缓存空间大小,默认程序分配最大空间的 1/8
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        int maxSize = manager.getMemoryClass() / RATE; // 比如 64M/8,单位为M
        // BitmapLruCache自定义缓存class，该框架本身支持二级缓存，在BitmapLruCache封装一个软引用缓存
        mImageLoader = new ImageLoader(RequestManager.getRequestQueue(),
                new BitmapLruCache(1024 * 1024 * maxSize));

        // CrashHandler crashHandler = CrashHandler.getInstance(); // 获取异常捕捉单例对象
        // crashHandler.init(getApplicationContext());
        File jsonCacheFile = new File(Environment.getExternalStorageDirectory()
                + Paths.JsonCache);
        if (!jsonCacheFile.exists()) {
            jsonCacheFile.mkdirs();
        }
        dataCache = DataCache.get(jsonCacheFile);

        // 获取个人登录本地存储的对象
        File userCacheFile = new File(Environment.getExternalStorageDirectory()
                + Paths.UserCache);
        if (!userCacheFile.exists()) {
            userCacheFile.mkdirs();
        }
        userCache = DataCache.get(userCacheFile);

        // 创建图片上传的文件夹
        File PHOTO_DIR = new File(Environment.getExternalStorageDirectory()
                .getPath() + Paths.UploadCache);
        if (!PHOTO_DIR.exists()) {
            PHOTO_DIR.mkdirs();
        }

        Fresco.initialize(this);
        ToastMgr.init(this);
        clearApkCache();
        comprareDay();
        //注册融云
        initRong();
        //注册激光推送
        initJpush();
        //设置高德地图
        setAmap();
    }

    private void initJpush() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
    }


    /**
     * 比对当前时间如果不是同一天删除相应的cache
     */
    private void comprareDay() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        if (ACacheHelper.getInstance().getDayInMonth(this) != day) {
            ACacheHelper.getInstance().saveDayInMonth(this, day);
            ACacheHelper.getInstance().saveVideoIndex(this, 0);
        }
    }


    public DataCache getCache() {
        return dataCache;
    }

    public DataCache getUserCache() {
        return userCache;
    }


    /**
     * 清除缓存目录
     *
     * @param dir 目录
     *            当前系统时间
     * @return
     */
    private int clearCacheFolder(File dir, long curTime) {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory()) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, curTime);
                    }
                    if (child.lastModified() < curTime) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return deletedFiles;
    }

    public void clearApkCache() {
        clearCacheFolder(new File(Environment.getExternalStorageDirectory()
                + Paths.ApkCache), System.currentTimeMillis());
    }

    public void clearImageCache() {
        clearCacheFolder(new File(Environment.getExternalStorageDirectory()
                + Paths.ApkImage), System.currentTimeMillis());
    }

    /**
     * 判断当前版本是否兼容目标版本的方法
     *
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    public static boolean hasExternalCacheDir() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

    /**
     * 检测sdcard是否可用
     *
     * @return true为可用，否则为不可用
     */
    public static boolean sdCardIsAvailable() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }

    //视频缓存
    private HttpProxyCacheServer proxy;

    public static HttpProxyCacheServer getProxy(Context context) {
        App app = (App) context.getApplicationContext();
        return app.proxy == null ? (app.proxy = app.newProxy()) : app.proxy;
    }

    private HttpProxyCacheServer newProxy() {
        //return new HttpProxyCacheServer(this);
        return new HttpProxyCacheServer.Builder(this).cacheDirectory(new File(Environment.getExternalStorageDirectory()
                + Paths.VideoCache)).build();
    }

    //初始化融云并且注册监听
    private void initRong() {


        /**
         * 注意：
         *
         * IMKit SDK调用第一步 初始化
         *
         * context上下文
         *
         * 只有两个进程需要初始化，主进程和 push 进程
         */
        if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext())) ||
                "io.rong.push".equals(getCurProcessName(getApplicationContext()))) {

            RongIM.init(this);

            /**
             * 融云SDK事件监听处理
             *
             * 注册相关代码，只需要在主进程里做。
             */
            if (getApplicationInfo().packageName.equals(getCurProcessName(getApplicationContext()))) {


                //扩展功能自定义
                InputProvider.ExtendProvider[] provider = {
                        new ImageInputProvider(RongContext.getInstance()),//图片
                        new CameraInputProvider(RongContext.getInstance()),//相机
//                        new LocationInputProvider(RongContext.getInstance()),//地理位置
                        new VoIPInputProvider(RongContext.getInstance()),// 语音通话

                };
                RongIM.getInstance().resetInputExtensionProvider(Conversation.ConversationType.PRIVATE, provider);

                Thread.setDefaultUncaughtExceptionHandler(new RongExceptionHandler(this));


                RongIM.setConversationBehaviorListener(new RongIM.ConversationBehaviorListener() {
                    @Override
                    public boolean onUserPortraitClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                        return false;
                    }

                    @Override
                    public boolean onUserPortraitLongClick(Context context, Conversation.ConversationType conversationType, UserInfo userInfo) {
                        return false;
                    }

                    @Override
                    public boolean onMessageClick(Context context, View view, Message message) {
                        if (message.getContent() instanceof ImageMessage) {
                            ImageMessage imageMessage = (ImageMessage) message.getContent();
                            Uri imageUri = imageMessage.getLocalUri() == null ? imageMessage.getRemoteUri() : imageMessage.getLocalUri();
                            List<String> imgUrls = new ArrayList<String>();
                            imgUrls.add(imageUri.toString());
                            ImagePagerActivity.startImagePagerActivity(context, imgUrls, 0);
                        }
                        return false;
                    }

                    @Override
                    public boolean onMessageLinkClick(Context context, String s) {
                        return false;
                    }

                    @Override
                    public boolean onMessageLongClick(Context context, View view, Message message) {
                        return false;
                    }
                });

            }
        }


    }


    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager
                .getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }


    public void setAuthKey(String authKey) {
        this.authKey = authKey;
    }


    //=========高德地图使用================
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public List<AMapLocationListener> listeners = new ArrayList<>();
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    StringBuilder sb = new StringBuilder();
                    //定位成功回调信息，设置相关消息
                    sb.append(aMapLocation.getLocationType() + "\n");//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    sb.append(aMapLocation.getLatitude() + "\n");//获取纬度
                    sb.append(aMapLocation.getLongitude() + "\n");//获取经度
                    sb.append(aMapLocation.getAccuracy() + "\n");//获取精度信息
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date(aMapLocation.getTime());
                    sb.append(df.format(date) + "\n");//定位时间
                    sb.append(aMapLocation.getAddress() + "\n");//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    sb.append(aMapLocation.getCountry() + "\n");//国家信息
                    sb.append(aMapLocation.getProvince() + "\n");//省信息
                    sb.append(aMapLocation.getCity() + "\n");//城市信息
                    sb.append(aMapLocation.getDistrict() + "\n");//城区信息
                    sb.append(aMapLocation.getStreet() + "\n");//街道信息
                    sb.append(aMapLocation.getStreetNum() + "\n");//街道门牌号信息
                    sb.append(aMapLocation.getCityCode() + "\n");//城市编码
                    sb.append(aMapLocation.getAdCode() + "\n");//地区编码
//                    aMapLocation.getAOIName();//获取当前定位点的AOI信息
                    Log.i("wanglei", "location:" + sb.toString());
                    if (listeners != null && listeners.size() > 0) {
                        for (AMapLocationListener listener : listeners) {
                            listener.onLocationChanged(aMapLocation);
                        }
                    }
                    city=aMapLocation.getCity();
                    mLocationClient.stopLocation();
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };

    private void setAmap() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    public void startLocation() {
        //启动定位
        mLocationClient.startLocation();
    }

    public void setLocationChangedLisenter(AMapLocationListener mLocationListener) {
        listeners.add(mLocationListener);
    }

    public String getCity(){
        return city;
    }
}